package com.hzb.LNReader;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.PrintWriter;
import java.io.Serializable;

import android.util.Log;

public class ReaderHistory implements Serializable {
	private static final long serialVersionUID = -3615126625347154286L;
	private static File configFile;
	
	private static final String LOG = "ReaderContext";
	
	public static ReaderRecord head;
	
	public static void loadFrom(File file) {
		configFile = file;
		if ((!file.exists()) || (!file.isFile())) return;
		
		try {
			BufferedReader in = new BufferedReader(new FileReader(file));
			try {
				ReaderRecord last = head = new ReaderRecord();
				
				for (;;) {
					String filePath = in.readLine();
					if (filePath == null) break;
					
					ReaderRecord record = new ReaderRecord();
					
					record.file = new File(filePath);
					record.fileSize = Integer.parseInt(in.readLine());
					record.maxLineSeq = Integer.parseInt(in.readLine());

					record.startLineSeq = Integer.parseInt(in.readLine());
					record.fileOffset = Integer.parseInt(in.readLine());
					record.scrollOffset = Integer.parseInt(in.readLine());
					
					record.encoding = in.readLine();
					
					record.lastReadTime = Long.parseLong(in.readLine());
					record.process = Integer.parseInt(in.readLine());
					record.summary = in.readLine();
					
					if (!record.file.isFile()) continue;
					record.prev = last;
					last.next = record;
					last = record;
				}
				
				head = head.next;
				head.prev = null;
			} finally {
				in.close();
			}
		} catch (Exception e) {
			Log.e(LOG, "Error loading config", e);
			head = null;
		}
	}
	
	public static void save() {
		try {
			PrintWriter out = new PrintWriter(configFile);
			try {
				ReaderRecord iter = head;
				for (;iter != null; iter = iter.next) {
					if (iter.file.isFile()) {
						out.println(iter.file.getAbsolutePath());
						out.println(iter.fileSize);
						out.println(iter.maxLineSeq);

						out.println(iter.startLineSeq);
						out.println(iter.fileOffset);
						out.println(iter.scrollOffset);
						
						out.println(iter.encoding);
						
						out.println(iter.lastReadTime);
						out.println(iter.process);
						out.println(iter.summary);
					} else {
						iter.remove();
					}
				}
			} finally {
				out.close();
			}
		} catch (Exception e) {
			Log.e(LOG, "Error saving config", e);
		}
	}
	
	public static ReaderRecord openReadHistory(File file) {
		ReaderRecord iter = head;
		for (;iter != null; iter = iter.next) {
			if (iter.file.equals(file)) {
				iter.offer();
				return iter;
			}
			
		}
		return new ReaderRecord(file);
	}
	
}


